package com.camera.handle.util;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class FileUtils {
    public static void main(String[] args)
    {
        String src="E:/DesktopFile/Android/CSDN.jpg";
        String target="E:/DesktopFile/Android/test/CSDN.jpg";
        copyFile(src,target);
    }
    public static void copyFile(String src,String target)
    {
        File srcFile = new File(src);
        File targetFile = new File(target);
        try {
            InputStream in = new FileInputStream(srcFile);
            OutputStream out = new FileOutputStream(targetFile);
            byte[] bytes = new byte[1024];
            int len = -1;
            while((len=in.read(bytes))!=-1)
            {
                out.write(bytes, 0, len);
            }
            in.close();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("文件复制成功");
    }


    public static void fileExist(String path){
        File file = new File(path);
        if(!file.exists()){
            file.mkdirs();
        }
    }

    public static void deleteFile(File file,int level){
        deleteFile(file,level,null);
    }

    public static void deleteFile(File file,int level,Long lastModified){
        try{
            //判断文件不为null或文件目录存在
            if (file == null || !file.exists()){
                System.out.println("文件删除失败,请检查文件路径是否正确");
                return;
            }
            //取得这个目录下的所有子文件对象
            File[] files = file.listFiles();
            //遍历该目录下的文件对象
            for (File f: files){
                //打印文件名
                String name = file.getName();
//            System.out.println(name);
                //判断子目录是否存在子目录,如果是文件则删除
                if (f.isDirectory()){
                    deleteFile(f,(level+1),lastModified);
                }else {
                    if(null!=lastModified&&lastModified.longValue()>0){
                        if(f.lastModified()<lastModified.longValue()){
                            f.delete();
                        }
                    }else{
                        f.delete();
                    }
                }
            }
            //删除空文件夹  for循环已经把上一层节点的目录清空。
            if(level>0){
                file.delete();
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }

}
